<?php

namespace payment\ttpay;

use \payment\notify;

class ttpay
{
    //文档地址 https://www.showdoc.com.cn/ttpays/1549229316592639
    //处理请求
    public function submit($payconfig, $params)
    {
        try {
            $service='wx.h5';
            if($params['pay_type']=='alipay'){
                $service='alipay.native';
            }
            $data = array(
                'app_id' => $payconfig['app_id'],
                'amount' => (float)$params['amount'],
                'subject' => $params['subject'],
                'service' => $service,
                //异步通知地址
                'out_trade_no' => $params['order_no'],

                'return_url' => $params['return_url']
            );
            //排序数组
            $data = $this->argSort($data);

            //加上密钥
            $data['sign'] = $this->makeSign($payconfig['secret'],$data);

            $url = 'http://api.ttpays.cn/api/v1/create';
            $res = $this->curlPost($url, $data);
            //^ "{"data":{"status_code":505,"desc":"\u652f\u4ed8\u6e20\u9053\u5f02\u5e38,\u8bf7\u8054\u7cfb\u5ba2\u670d","out_trade_no":"202108251535416125f2cd429a5","type":"ALI","tool":"SCCANPAY","amount":"1.60","create_time":1629877407},"code":0,"message":"success","error":null,"date":"2021-08-25 15:43:27"}"
            $resArr=json_decode($res,true);
//            dd($resArr);
//            ^ array:5 [
//                "data" => array:8 [
//                "status_code" => 0
//    "desc" => "SUCCESS"
//    "out_trade_no" => "202108251545086125f504685ba"
//    "type" => "wx.h5"
//    "tool" => "SCCANPAY"
//    "amount" => "0.90"
//    "result" => "https://api.ttpays.cn/api/v1/pay/e13f09bbce877aa72154e5d3a3c46608"
//    "create_time" => 1629877511
//  ]
//  "code" => 0
//  "message" => "success"
//  "error" => null
//  "date" => "2021-08-25 15:45:11"
//]
            if(isset($resArr['data']['status_code'])&&$resArr['data']['status_code']==0){

                $result = array(
                    'type' => 1,
                    'subjump' => 0,
                    'paymethod' => $params['pay_type'],
                    'url' => $resArr['data']['result'],
                    'payname' => $params['subject'],

                    'money' => $params['amount']
                );
                return array('code' => 1, 'msg' => 'success', 'data' => $result);
            }else{
                return array('code'=>1001,'msg'=>'支付接口请求失败：'.json_encode($resArr),'data'=>$resArr);
            }
        } catch (\Exception $e) {
            return array('code' => 1000, 'msg' => $e->getMessage(), 'data' => '');
        }
    }

    //处理回调
    public function notify($payconfig)
    {
//        {
//            "out_trade_no":"201900125556703893",
//    "trade_no":"201900124537701521",
//    "amount":"1.00",
//    "status":"FINISHED",
//    "sign":"378259136ad5e86255f3cc0818b522507f687cb9"
//}
        try {
            //获取传入数据
            $params = $_POST;
            //去除空值和签名参数
            $params = $this->paraFilter($params);
            //排序
            $params = $this->argSort($params);
            //排序数组



            //签名
            $md5Sigm = $this->makeSign($payconfig['secret'],$params);
            // 验证签名数据
            if ($md5Sigm == $_POST['sign'] && $params['status'] == 'FINISHED') {
                //成功
                //商户订单号
                $ret = array(
                    'tradeid' => $params['trade_no'],
                    'paymoney' => $params['amount'],
                    'orderid' => $params['out_trade_no']
                );
                $notify = new notify();
                $data = $notify->run($ret);
                if ($data['code'] > 1) {
                    return 'error|Notify: ' . $data['msg'];
                } else {
                    return 'success';
                }
            } else {
                return 'error|Notify: auth fail';
            }

        } catch (\Exception $e) {
            file_put_contents(YEWU_FILE, CUR_DATETIME . '-' . $e->getMessage() . PHP_EOL, FILE_APPEND);
            exit;
        }
    }

    //订单退款
    public function refund($payconfig, $order_no, $money, $reson = '')
    {
        $config = array(
            //商户id
            'app_id' => $payconfig['app_id'],
            'out_trade_no' => $order_no
        );
        //排序数组
        $config = $this->argSort($config);
        // 转换成参数状态
        $config['sign'] = $this->makeSign($this->createLinkstring($config) . $payconfig['app_secret']);
        //获取url
        $url = 'http://api.ttpays.cn/api/v1/refund';

        $res = $this->curlPost($url, $config);
        file_put_contents(YEWU_FILE, CUR_DATETIME . '-退款结果回调：' . $res . PHP_EOL, FILE_APPEND);
        $ress = json_decode($res, true);
        if (isset($ress['code']) && $ress['code'] == 200) {
            return ['status' => 1];
        } else {
            return ['status' => 0, 'back_error' => $ress['msg']];
        }
    }

    function makeSign($secret, array $data)
    {
        if (!is_null($secret)) {
            ksort($data);
            $data['signKey'] = $secret;
            $str = json_encode($data);
            return sha1($str);
        }
        return false;
    }

    /**
     * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param $para 需要拼接的数组
     * return 拼接完成以后的字符串
     */
    function createLinkstring($para)
    {

        $arg = "";
        foreach ($para as $key => $val) {
            $arg .= $key . "=" . $val . "&";
        }
        //去掉最后一个&字符
        $arg = substr($arg,0,strlen($arg)-1);

        //如果存在转义字符，那么去掉转义
        if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()){
            $arg = stripslashes($arg);
        }
        return $arg;
    }

    /**
     * 除去数组中的空值和签名参数
     * @param $para 签名参数组
     * return 去掉空值与签名参数后的新签名参数组
     */
    function paraFilter($para)
    {
        $para_filter = array();
        foreach ($para as $key => $val) {
            if ($key == "sign" || $key == "sign_type" || $val == "" || $key == 'paymethod') continue;
            else    $para_filter[$key] = $para[$key];
        }
        return $para_filter;
    }
    /**
     * 对数组排序
     * @param $para 排序前的数组
     * return 排序后的数组
     */
    function argSort($para)
    {
        ksort($para);
        reset($para);
        return $para;
    }


    public function curlPost($url = '', $postData = '', $options = array())
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}
